<template>
  <div class="app-container" style="padding-top: 0">
    <!-- 骨架屏 -->
    <mobile-skeleton 
      v-if="loading" 
      :showHeader="true"
      :showSearch="false"
      :showCards="false"
      :showTable="true"
      :tableColumns="5"
      :tableRows="5"
      :showPagination="false"
    />
    
    <template v-else>
      <!-- 页面头部 -->
      <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start">
        <el-col :span="1">
          <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer; margin-left: 10px"
            @click="handleBack" /></el-col>
        <el-col :span="23">
          <h3 :style="{ color: theme }">培训统计</h3>
        </el-col>
      </el-row>
      
      <!-- 桌面端布局 -->
      <div v-if="!isMobile">
        <el-form ref="postForm" label-position="left" label-width="120px">
          <el-card style="padding-top: 20px">
            <el-descriptions class="margin-top" :column="3" border>
              <el-descriptions-item v-if="data.name && data.name !== undefined">
                <template slot="label"> 培训名称 </template>
                {{ data.name }}
              </el-descriptions-item>
              <el-descriptions-item v-if="data && data.course !== undefined && data.course.name !== undefined">
                <template slot="label"> 关联课程 </template>
                {{ data.course.name }}
              </el-descriptions-item>
              <el-descriptions-item v-if="data.start_time !== undefined && data.end_time !== undefined">
                <template slot="label"> 培训时间 </template>
                {{ data.start_time }} 至 {{ data.end_time }}
              </el-descriptions-item>
              <el-descriptions-item v-if="data.user !== undefined">
                <template slot="label"> 应培训人数 </template>
                {{ data.user.length }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">完成培训人数 </template>
                {{ passeds.length }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 培训状态 </template>
                <el-tag size="small"> {{ data.state | stateFilter }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 明细 -->
          <h3 :style="{ color: theme }">明细情况</h3>
          <el-card style="margin-top: 20px">
            <div class="table-operations">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </div>
            <el-table :data="data.user" style="width: 100%; margin-bottom: 20px" row-key="id" border size="mini">
              <el-table-column label="序号" min-width="40">
                <template slot-scope="scope">
                  {{ (queryParams.page - 1) * queryParams.page_size + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="员工" width="180">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column label="部门" width="180">
                <template slot-scope="scope">
                  {{ scope.row.dept }}
                </template>
              </el-table-column>
              <el-table-column label="岗位" width="220">
                <template slot-scope="scope" v-if="scope.row.post && scope.row.post.length > 0">
                  <span>{{ scope.row.post[0].name }}</span>
                </template>
                <template v-else>
                  <span>暂无关联岗位</span>
                </template>
              </el-table-column>

              <el-table-column label="关联课程" v-if="data.course !== undefined && data.course.name !== undefined"> {{
                data.course.name
              }} </el-table-column>
              <el-table-column label="培训次数">
                <template slot-scope="scope">
                  {{ scope.row.train.count }}
                </template>
              </el-table-column>
              <el-table-column label="学习情况">
                <template slot-scope="scope">
                  <span :style="scope.row.train.is_passed == false ? { color: 'red' } : { color: theme }"> {{
                    scope.row.train.is_passed | passedFilter }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form>
      </div>
      
      <!-- 移动端布局 -->
      <div v-else class="mobile-view">
        <!-- 培训基本信息卡片 -->
        <el-card class="mobile-card">
          <div class="card-title" :style="{ color: theme }">培训基本信息</div>
          <div class="mobile-info-list">
            <div class="info-item" v-if="data.name && data.name !== undefined">
              <span class="info-label">培训名称：</span>
              <span class="info-value">{{ data.name }}</span>
            </div>
            <div class="info-item" v-if="data && data.course !== undefined && data.course.name !== undefined">
              <span class="info-label">关联课程：</span>
              <span class="info-value">{{ data.course.name }}</span>
            </div>
            <div class="info-item" v-if="data.start_time !== undefined && data.end_time !== undefined">
              <span class="info-label">培训时间：</span>
              <span class="info-value">{{ data.start_time }} 至 {{ data.end_time }}</span>
            </div>
            <div class="info-item" v-if="data.user !== undefined">
              <span class="info-label">应培训人数：</span>
              <span class="info-value">{{ data.user.length }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">完成培训人数：</span>
              <span class="info-value">{{ passeds.length }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">培训状态：</span>
              <span class="info-value">
                <el-tag size="small">{{ data.state | stateFilter }}</el-tag>
              </span>
            </div>
          </div>
        </el-card>
        
        <!-- 明细情况 -->
        <div class="mobile-section-title" :style="{ color: theme }">明细情况</div>
        <div class="mobile-export-btn">
          <el-button 
            type="warning" 
            plain 
            icon="el-icon-download" 
            size="small" 
            @click="handleExport"
            style="width: 100%">
            导出数据
          </el-button>
        </div>
        
        <!-- 显示方式切换 -->
        <div class="mobile-view-toggle">
          <el-radio-group v-model="mobileViewMode" size="small">
            <el-radio-button label="card">卡片视图</el-radio-button>
            <el-radio-button label="list">列表视图</el-radio-button>
          </el-radio-group>
        </div>
        
        <!-- 移动端卡片列表 -->
        <div v-if="mobileViewMode === 'card'" class="mobile-card-list" v-show="data.user && data.user.length > 0">
          <el-card 
            v-for="(item, index) in data.user" 
            :key="index"
            class="mobile-card user-card"
            shadow="hover">
            <div class="user-info">
              <div class="user-name" :style="{ color: theme }">{{ item.name }}</div>
              <div class="user-status">
                <el-tag 
                  size="mini" 
                  :type="item.train.is_passed ? 'success' : 'danger'">
                  {{ item.train.is_passed | passedFilter }}
                </el-tag>
              </div>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="info-label">部门：</span>
                <span class="info-value">{{ item.dept }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">岗位：</span>
                <span class="info-value">{{ item.post && item.post.length > 0 ? item.post[0].name : '暂无关联岗位' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">培训次数：</span>
                <span class="info-value">{{ item.train.count }}</span>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 移动端列表视图 -->
        <div v-else-if="mobileViewMode === 'list'" class="mobile-list-view">
          <el-collapse v-if="data.user && data.user.length > 0" accordion>
            <el-collapse-item 
              v-for="(item, index) in data.user" 
              :key="index"
              :name="index"
              :title="item.name">
              <template slot="title">
                <span class="list-title">
                  <span>{{ item.name }}</span>
                  <el-tag 
                    size="mini" 
                    :type="item.train.is_passed ? 'success' : 'danger'">
                    {{ item.train.is_passed | passedFilter }}
                  </el-tag>
                </span>
              </template>
              
              <div class="detail-table">
                <div class="detail-row">
                  <div class="detail-label">部门</div>
                  <div class="detail-value">{{ item.dept }}</div>
                </div>
                <div class="detail-row">
                  <div class="detail-label">岗位</div>
                  <div class="detail-value">{{ item.post && item.post.length > 0 ? item.post[0].name : '暂无关联岗位' }}</div>
                </div>
                <div class="detail-row">
                  <div class="detail-label">培训次数</div>
                  <div class="detail-value">{{ item.train.count }}</div>
                </div>
                <div class="detail-row">
                  <div class="detail-label">关联课程</div>
                  <div class="detail-value">{{ data.course && data.course.name ? data.course.name : '暂无关联课程' }}</div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        
        <!-- 无数据提示 -->
        <el-empty 
          v-if="!data.user || data.user.length === 0" 
          description="暂无培训人员数据" 
          :image-size="120">
        </el-empty>
        
        <!-- 培训统计摘要 -->
        <div class="mobile-stats-summary" v-if="data.user && data.user.length > 0">
          <div class="summary-title" :style="{ color: theme }">培训结果统计</div>
          <div class="stats-cards">
            <div class="stats-card">
              <div class="stats-value">{{ data.user.length }}</div>
              <div class="stats-label">总人数</div>
            </div>
            <div class="stats-card">
              <div class="stats-value">{{ passeds.length }}</div>
              <div class="stats-label">已通过</div>
            </div>
            <div class="stats-card">
              <div class="stats-value">{{ data.user.length - passeds.length }}</div>
              <div class="stats-label">未通过</div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import RepoSelect from "@/components/RepoSelect";
import { mapGetters, mapState } from "vuex";
import { statisticsTrain, trainTestDetail } from "@/api/vadmin/train/train";
import variables from "@/assets/styles/variables.scss";
import backImg from "@/assets/images/back.png";
import MobileSkeleton from "@/components/MobileSkeleton";
// 导入导出所需的库
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';

export default {
  name: "ExamDetail",
  components: { RepoSelect, MobileSkeleton },
  data() {
    return {
      loading: true,
      backImg: backImg,
      postForm: { course: { name: "", id: "" }, user: [] },
      queryParams: {
        page_size: 10,
        page: 1,
      },
      passeds: [],
      is_passeds: {
        false: "不合格",
        true: "合格",

      },
      trainId: '',
      data: [],
      plan_data: [],//应参加培训人员
      isMobile: false,
      mediaQueryList: null,
      mobileViewMode: 'card' // 新增：移动端视图模式，默认卡片视图
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  watch: {},
  filters: {
    stateFilter(val) {
      const state = {
        false: "停用",
        true: "启用",
      };
      return state[val];
    },
    passedFilter(val) {
      const is_passed = {
        false: "未通过",
        true: "已通过",
        null: "未通过",
      };
      return is_passed[val];
    },
  },
  created() {
    if (this.$route.query.train) {
      this.trainId = this.$route.query.train
      this.plan_data = this.$route.query.user
      this.getTrainCount()
    }
    
    // 初始化移动设备状态
    this.isMobile = document.body.clientWidth < 768;
    // 监听屏幕宽度变化
    this.mediaQueryList = window.matchMedia("(max-width: 768px)");
    this.mediaQueryList.addListener(this.handleScreenWidthChange);
  },
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
    // 移除屏幕宽度变化监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.handleScreenWidthChange);
    }
  },
  methods: {
    getTrainCount() {
      trainTestDetail(this.trainId).then(res => {
        this.loading = false
        this.data = res
        this.data.user.forEach((item) => {
          if (item.train.is_passed == true) {
            this.passeds.push(item);
          }
        });
      })
    },
    passedFormatter(row) {
      return this.is_passeds[row.is_passed];
    },
    handleBack() {
      this.$router.back()//返回浏览器上一页，并保留上一页数据
    },
    // 移动端屏幕宽度变化处理
    handleScreenWidthChange(e) {
      this.isMobile = e.matches;
    },
    handleExport() {
      this.$confirm('确认导出培训统计数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'info',
          message: '正在导出数据，请稍候...'
        });
        
        // 设置表头和字段名
        const tHeader = ['序号', '员工', '部门', '岗位', '关联课程','培训次数', '学习情况'];
        const filterVal = ['index', 'name', 'dept', 'post', 'course', 'count', 'passed'];
        
        // 格式化数据
        const list = this.data.user.map((item, index) => {
          return {
            index: index + 1,
            name: item.name,
            dept: item.dept,
            post: item.post && item.post.length > 0 ? item.post[0].name : '暂无关联岗位',
            course: this.data.course && this.data.course.name ? this.data.course.name : '暂无关联课程',
            count: item.train.count,
            passed: item.train.is_passed ? '已通过' : '未通过'
          };
        });
        
        // 导出Excel
        this.exportToExcel(tHeader, filterVal, list);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
    },
    exportToExcel(tHeader, filterVal, list) {
      try {
        // 格式化表格数据
        const data = this.formatJson(filterVal, list);
        
        // 创建包含培训基本信息的前两行，确保与tHeader列数一致
        const trainingInfo = [
          ['培训名称', this.data.name || '', '关联课程', this.data.course && this.data.course.name ? this.data.course.name : '', '培训时间', `${this.data.start_time || ''} 至 ${this.data.end_time || ''}`, ''],
          ['应培训人数', this.data.user ? this.data.user.length : 0, '完成培训人数', this.passeds.length, '培训状态', this.data.state ? '启用' : '停用', '']
        ];
        
        // 添加表头和数据
        const allData = [...trainingInfo, ['','','','','','',''], tHeader, ...data];
        
        // 创建工作簿和工作表
        const ws = XLSX.utils.aoa_to_sheet(allData);
        const wb = XLSX.utils.book_new();
        
        // 设置列宽
        const wscols = tHeader.map((col, index) => {
          // 根据内容设置列宽
          let maxLength = 15; // 默认宽度
          allData.forEach(row => {
            const cellValue = row[index] ? row[index].toString() : '';
            const cellLength = cellValue.toString().charCodeAt(0) > 255 
              ? cellValue.length * 2 // 中文宽度加倍
              : cellValue.length;
            maxLength = Math.max(maxLength, cellLength);
          });
          return { wch: maxLength + 2 }; // 额外增加一些宽度
        });
        
        ws['!cols'] = wscols;
        
        // 添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        
        // 生成文件名
        const fileName = `培训统计_${this.data.name || '详情'}_${new Date().getTime()}.xlsx`;
        
        // 导出文件
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName);
        
        this.$message({
          message: '导出成功',
          type: 'success'
        });
      } catch (error) {
        console.error('导出失败:', error);
        this.$message({
          message: '导出失败，请重试',
          type: 'error'
        });
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    }
  },
};
</script>

<style lang="scss" scoped>
.pre-exam div {
  line-height: 42px;
  color: #555555;
}

.post-tree {
  border: 1px solid #dcdfe6;
}

.el-tree {
  z-index: 2;
}

.table-operations {
  margin-bottom: 10px;
  text-align: right;
}

.ct_table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px !important;
  padding: 10px 0;

  tr {
    height: 40px;
  }

  td {}

  .tb_head {
    font-size: 16px;
    font-weight: 400;
    width: 140px;
    padding: 10px 0;
    background: #e4e4e4;
    padding-left: 20px;
  }

  .custom-table-td {
    width: 200px;
    font-size: 16px;
    font-weight: 400;
    color: #333333;
    padding: 10px 20px 10px;
  }

  .w180 {
    width: 180px;
  }
}

/* 移动端适配样式 */
@media screen and (max-width: 768px) {
  .app-container {
    padding: 0 10px !important;
  }
  
  .test_header {
    padding: 10px 0;
    
    h3 {
      font-size: 18px;
      margin: 0;
    }
  }
  
  .el-descriptions {
    margin-top: 10px !important;
    
    &.el-descriptions--border {
      .el-descriptions-item__label {
        width: 80px;
        padding: 8px 10px;
      }
      
      .el-descriptions-item__content {
        padding: 8px 10px;
      }
    }
  }
  
  .el-card {
    margin-bottom: 15px;
    border-radius: 8px;
  }
  
  .el-table {
    font-size: 12px;
    
    th {
      padding: 8px 0;
    }
    
    td {
      padding: 8px 0;
    }
    
    .cell {
      padding-left: 5px;
      padding-right: 5px;
    }
  }
  
  .table-operations {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 15px;
    
    .el-button {
      flex: 0 0 auto;
    }
  }
  
  /* 移动端卡片和信息样式 */
  .mobile-view {
    padding: 0 5px;
    padding-bottom: 60px; /* 添加底部安全间距，防止被遮挡 */
  }
  
  .mobile-card {
    margin-bottom: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    
    .card-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f0f0f0;
    }
  }
  
  .mobile-info-list {
    .info-item {
      display: flex;
      margin-bottom: 12px;
      align-items: flex-start;
      flex-wrap: wrap; /* 允许内容换行 */
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .info-label {
        flex: 0 0 85px;
        color: #606266;
        font-size: 14px;
      }
      
      .info-value {
        flex: 1;
        color: #333;
        word-break: break-all; /* 允许在任何字符间断行 */
        min-width: 0; /* 确保flex项目可以缩小到小于其内容大小 */
      }
    }
  }
  
  .mobile-section-title {
    font-size: 16px;
    font-weight: bold;
    margin: 20px 0 15px;
    position: relative;
    padding-left: 10px;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: currentColor;
      border-radius: 2px;
    }
  }
  
  .mobile-export-btn {
    margin-bottom: 15px;
  }
  
  .mobile-view-toggle {
    margin-bottom: 15px;
    text-align: center;
    
    .el-radio-button__inner {
      padding: 8px 15px;
    }
  }
  
  .mobile-card-list {
    .user-card {
      margin-bottom: 12px;
      
      .user-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 1px solid #f0f0f0;
        
        .user-name {
          font-size: 16px;
          font-weight: bold;
        }
      }
      
      .info-list {
        .info-item {
          display: flex;
          margin-bottom: 8px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .info-label {
            flex: 0 0 70px;
            color: #909399;
          }
          
          .info-value {
            flex: 1;
            color: #606266;
            word-break: break-all;
          }
        }
      }
    }
  }
  
  /* 列表视图样式 */
  .mobile-list-view {
    margin-bottom: 20px;
    
    .el-collapse-item__header {
      font-size: 15px;
      height: auto;
      line-height: 1.5;
      padding: 10px;
      display: flex;
      align-items: center;
    }
    
    .list-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      overflow: hidden;
      
      span:first-child {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 5px;
      }
    }
    
    .detail-table {
      width: 100%;
      border-radius: 4px;
      overflow: hidden;
      background-color: #f9f9f9;
      
      .detail-row {
        display: flex;
        flex-wrap: wrap; /* 确保在小屏幕上可以换行 */
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .detail-label {
          flex: 0 0 70px;
          padding: 10px;
          background-color: #f0f0f0;
          color: #606266;
          font-weight: 500;
        }
        
        .detail-value {
          flex: 1;
          padding: 10px;
          color: #606266;
          word-break: break-all;
          min-width: 0; /* 确保flex项目可以缩小 */
          overflow-wrap: break-word; /* 允许长单词换行 */
        }
      }
    }
  }
  
  /* 统计摘要样式 */
  .mobile-stats-summary {
    margin-top: 20px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    
    .summary-title {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
    }
    
    .stats-cards {
      display: flex;
      justify-content: space-around;
      
      .stats-card {
        text-align: center;
        flex: 1;
        
        .stats-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;
        }
        
        .stats-label {
          font-size: 13px;
          color: #606266;
        }
        
        &:nth-child(2) .stats-value {
          color: #67c23a;
        }
        
        &:nth-child(3) .stats-value {
          color: #f56c6c;
        }
      }
    }
  }
  
  /* 添加全局移动端修复样式 */
  .el-collapse-item__content {
    padding-bottom: 15px;
  }
  
  /* 修复Element UI在移动端的可能溢出问题 */
  .el-collapse-item__wrap,
  .el-collapse-item__header,
  .el-card__body {
    overflow: visible;
  }
  
  /* 确保标签在移动设备上不会被截断 */
  .el-tag {
    max-width: 100%;
    margin: 2px 0;
  }
  
  /* 确保表格内容在移动设备上能完全显示 */
  .el-table {
    width: 100% !important;
    
    .cell {
      word-break: break-all;
    }
  }
  
  /* 处理潜在的z-index问题，防止部分内容被遮挡 */
  .mobile-card-list,
  .mobile-list-view,
  .mobile-stats-summary {
    position: relative;
    z-index: 1;
  }
}
</style>
